package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.User_ManagementDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = User_ManagementService.class)
@Transactional
public class User_ManagementServiceImpl implements User_ManagementService {
    @Autowired
    private User_ManagementDao user_managementDao;
    //分页查询
    public PageResult findPage(QueryPageBean pageBean) {
        Integer currentPage = pageBean.getCurrentPage();
        Integer pageSize = pageBean.getPageSize();
        String queryString = pageBean.getQueryString();
        //使用分页助手插件实现分页查询
        PageHelper.startPage(currentPage,pageSize);
        Page<User> page = user_managementDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Role> findAll() {
        return user_managementDao.findAll();
    }



        //编辑检查项信息，同时需要设置关联关系
        public void edit(Role role, Integer[] checkitemIds) {
            //基本信息修改
            user_managementDao.edit(role);
            //清理检查组和检查项的关联关系（操作中间关系表）
            user_managementDao.deleteAssociation(role.getId());
            //重新建立检查组和检查项的关联关系
            this.setCheckGroupAndCheckItem(role.getId(),checkitemIds);
        }

    @Override
    public void add(User user) {
        user_managementDao.add(user);
    }

    public void setCheckGroupAndCheckItem(Integer roleId,Integer[] checkitemIds) {
        //设置多对多关系
        if (checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {//检查项id
                Map<String, Integer> map = new HashMap<>();
                map.put("roleId", roleId);
                map.put("checkitemId", checkitemId);
                user_managementDao.setCheckGroupAndCheckItem(map);
            }
        }
    }

}
